/*
 * @Author: wuyuxin
 * @Date: 2022-01-10 16:41:57
 * @LastEditors: wuyuxin
 * @LastEditTime: 2022-01-12 11:23:10
 * @Description: 
 */
import { BOOTSTRAPPING, LOADING_SOURCE_CODE, MOUNTED, NOT_BOOTSTRAPPED, NOT_LOADED, shouldBeActive, SKIP_BECAUSE_BROKEN } from "./app.helpers";
import { reroute } from "../navigations/reroute";
const apps = []; // 用来存放所有的应用

/**
 * @Author: wuyuxin
 * @description: 
 * @param {*} appName 应用名字
 * @param {*} loadApp 加载的应用
 * @param {*} activeWhen 当激活时会调用 loadApp
 * @param {*} customProps 自定义属性
 * @return {*}
 */
// 维护应用的所有的状态， 状态机
export function registerApplication(appName, loadApp, activeWhen, customProps) {
  apps.push({ // 这里就将应用注册好了
    name: appName,
    loadApp,
    activeWhen,
    customProps,
    status: NOT_LOADED
  });
  reroute(); // 加载应用
  // console.log(apps)
}

export function getAppChanges() {
  const appsToUnmount = []; // 需要卸载的app
  const appsToLoad = []; // 需要加载的app
  const appsToMount = []; // 需要挂载的app
  apps.forEach(app => {
    // const appShouldBeActive = app.status !== SKIP_BECAUSE_BROKEN && shouldBeActive(app); 
    const appShouldBeActive = shouldBeActive(app); // 先不考虑出错的情况
    switch (app.status) {
      case NOT_LOADED:
      case LOADING_SOURCE_CODE:
        if (appShouldBeActive) {
          appsToLoad.push(app);
        }
        break;
      case NOT_BOOTSTRAPPED:
      case BOOTSTRAPPING:
      case NOT_LOADED:
        if (appShouldBeActive) {
          appsToMount.push(app);
        }
        break;
      case MOUNTED: // toUnmount
        if(!appShouldBeActive){
          appsToUnmount.push(app);
        }
        break;
      default:
        break;
    }
  })
  return {appsToUnmount,appsToLoad,appsToMount}
}